package com.frogs.ucenter.service.impl;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.entity.IndexNewCoupon;
import com.frogs.ucenter.entity.UserCoupon;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.CouponService;

@Service("couponService")
public class CouponServiceImpl extends AbsService implements CouponService {

	private static Logger log = LoggerFactory.getLogger(CouponServiceImpl.class);
	

	public JSONObject getCouponList(Integer pageNo, Integer pageSize,
			Integer userId,Integer applicablePlatformId,Integer status)  throws Exception {
		ApiUrl apiUrl = this.buildPromotionApiBaseUrl("PROMOTION_USER_COUPON_LIST");
		String[] otherParams = {ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.applicablePlatformId.getParamName(),"3",
								ApiUrlParamEnum.couponStatus.getParamName(),status.toString(),
								ApiUrlParamEnum.pageSize.getParamName(),pageSize.toString(),
								ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		}
		catch(IllegalStateException e){
			log.error("func[getCouponList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		catch (Exception e) {
			throw new Exception("用户优惠劵接口异常！");
		}
		return result;
	}
	
	public JSONObject getNewCouponList(Integer pageNo, Integer pageSize
			,Integer applicablePlatformId)  throws Exception {
		ApiUrl apiUrl = this.buildPromotionApiBaseUrl("PROMOTION_COUPON_LIST");
		String[] otherParams = {ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.applicablePlatformId.getParamName(),"3",
								ApiUrlParamEnum.pageSize.getParamName(),pageSize.toString(),
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		}
		catch(IllegalStateException e){
			log.error("func[getCouponList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		catch (Exception e) {
			throw new Exception("获取最新优惠劵接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject showCoupon(Integer userId, Integer couponId) {
		return null;
	}

	@Override
	public PageList<UserCoupon> getCouponsByUserId(Integer pageNo,
			Integer pageSize, Integer userId,Integer applicablePlatformId,Integer status) throws Exception {
		PageList<UserCoupon> uCoupons = null;
		JSONObject userCoupons = this.getCouponList(pageNo, pageSize, userId,applicablePlatformId,status);
		int code = userCoupons.getJSONObject("response").getIntValue("code");
		if(code != ApiResultEnum.SUCCESS.getId()){
			return null;
		}else{
			JSONArray couponArrayJson = userCoupons.getJSONObject("response").getJSONArray("list");
	    	Calendar calendar = Calendar.getInstance();
	    	uCoupons = new PageList<UserCoupon>();
	    	//Integer couponStatus = 0;
	    	if (couponArrayJson != null) {
	    		for(int i = 0; i<couponArrayJson.size(); i++) {
		    		JSONObject jsonObj = couponArrayJson.getJSONObject(i);
		    		UserCoupon uc = new UserCoupon();
		    		uc.setCouponName(jsonObj.getString("cardTitle"));
		    		//couponStatus = couponS.getInteger("cpStatus");
		    		uc.setCouponDescribe(jsonObj.getString("cardDetail"));
		    		uc.setCouponValue(jsonObj.getString("reduceValue"));
		    		calendar.setTimeInMillis(Long.parseLong(jsonObj.getString("endTime")));
		    		uc.setEndTime(DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd"));
		    		uc.setStartTime(DateUtil.formatDate(new Date(Long.parseLong(jsonObj.getString("beginTime"))), "yyyy-MM-dd"));
		    		uc.setImgUrl(jsonObj.getString("imgUrl"));
		    		//uc.setIsTimes(jsonObj.getString("isTimes"));
		    		uc.setMinAmount(jsonObj.getString("leastCost"));
		    		uc.setSnNumber(jsonObj.getString("code"));
		    		uc.setUseCount(jsonObj.getString("useCount"));
		    		//String useDate = jsonObj.getString("usedDate");
//		    		if(useDate.length()>0){
//		    			uc.setUsedDate(DateUtil.Milliscond.format2Str(Long.parseLong(jsonObj.getString("usedDate")),"yyyy-MM-dd"));
//		    		}
		    		uc.setUsePlatform(jsonObj.getString("bindPlatform"));
		    		uCoupons.add(uc);
		    		uCoupons.setPageTurn(JSON.toJavaObject(userCoupons.getJSONObject("response").getJSONObject("pageTurn"), PageTurn.class));
		    	}
	    	}
	    	return uCoupons;
		}
	}

	@Override
	public PageList<IndexNewCoupon> getNewCoupons(Integer pageNo, Integer pageSize,
			Integer applicablePlatformId) throws Exception {
		// TODO Auto-generated method stub
		PageList<IndexNewCoupon> newCoupons = null;
		JSONObject newCouponsJSON = this.getNewCouponList(pageNo, pageSize, applicablePlatformId);
		int code = newCouponsJSON.getJSONObject("response").getIntValue("code");
		if(code != ApiResultEnum.SUCCESS.getId()){
			return null;
		}else{
			JSONArray couponArrayJson = newCouponsJSON.getJSONObject("response").getJSONArray("list");
	    	newCoupons = new PageList<IndexNewCoupon>();
	    	//Integer couponStatus = 0;
	    	if (couponArrayJson != null) {
	    		for(int i = 0; i<couponArrayJson.size(); i++) {
		    		JSONObject jsonObj = couponArrayJson.getJSONObject(i);
		    		IndexNewCoupon uc = new IndexNewCoupon();
		    		uc.setCouponName(jsonObj.getString("title"));
		    		uc.setCouponDescribe(jsonObj.getString("detail"));
		    		uc.setImgUrl(jsonObj.getString("imgUrl"));
		    		uc.setId(jsonObj.getInteger("id"));
		    		newCoupons.add(uc);
		    		newCoupons.setPageTurn(JSON.toJavaObject(newCouponsJSON.getJSONObject("response").getJSONObject("pageTurn"), PageTurn.class));
		    	}
	    	}
	    	return newCoupons;
		}
	}

}
